import { UserInfo } from '@shared/types.d';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';

import * as userApi from '@/api/system/user';

export const useUserStore = defineStore(
  'user',
  () => {
    // 状态
    const currentUser = ref<UserInfo | null>(null);
    const authToken = ref<string | null>(null); // JWT token

    // 计算属性
    const isLoggedIn = computed(() => !!currentUser.value && !!authToken.value);
    const currentUserId = computed(() => currentUser.value?.id || null);
    const currentUserName = computed(() => currentUser.value?.name || '');
    const hasValidToken = computed(() => !!authToken.value);

    // 用户登录并获取JWT token
    const login = async (userId: string): Promise<boolean> => {
      const response = await userApi.login(userId);
      if (response.success && response.data) {
        authToken.value = response.data.token;
        currentUser.value = response.data.user;
        return true;
      }

      throw new Error(response.message || '登录失败');
    };

    // 登出
    const logout = async (): Promise<void> => {
      if (currentUser.value) {
        try {
          await userApi.logout(currentUser.value.id);
        } finally {
          authToken.value = null;
          currentUser.value = null;
        }
      }
    };

    return {
      // 状态
      currentUser,
      authToken,

      // 计算属性
      isLoggedIn,
      currentUserId,
      currentUserName,
      hasValidToken,

      login,
      logout
    };
  },
  {
    persist: {
      key: 'user-store',
      storage: localStorage
    }
  }
);
